<?php


namespace App\Http\Controllers\Mini\Circle;


use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\FleaOrder;
use App\Models\FleaRecord;
use App\Models\Mini\FleaGoodsModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 * Class FleaOrderController
 * @package App\Http\Controllers\Mini\Circle
 * 邻里圈 跳蚤市场 订单控制器
 */
class FleaOrderController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();
        $this->user_id = $id;
    }

    /**
     * 用户下单接口
     */
    public function store(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }
        $data = $request->post();

        $validator = Validator::make($data, [
            'goods_id' => 'required',
            'num' => 'required|integer',
            'deal_type' => 'required|in:1,2',
            'address_id' => 'required|integer'
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors();
            return $this->error($errors->first());
        }

        $goods = FleaGoodsModel::query()->where('id', $data['goods_id'])->first();

        $check = $this->checkGoods($goods, $data['num']);

        if ($check !== true) {
            return $this->error($check);
        }


        $data['user_id'] = $user_id;
        $data['amount'] = $goods['goods_price'];
        $data['total_amount'] = $goods['goods_price'] * $data['num'];
        $data['address'] = $goods['address'];
        //查询用户收货地址信息
        $data['user_address'] = Address::query()->where('id', $data['address_id'])->select('receive_name', 'receive_tel', 'area_info', 'address')->firstOrFail()->toJson(JSON_UNESCAPED_UNICODE);
        //生成订单号
        $data['order_sn'] = 'Flea' . makeOrderSn();
        unset($data['address_id']);

        DB::beginTransaction();
        try {
            FleaOrder::query()->create($data);
            //商品状态改为已拍下代付款
            FleaGoodsModel::query()->where('id', $data['goods_id'])->update(['is_sale' => 2]);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success(['order_sn' => $data['order_sn']], '下单成功');
    }

    /**
     * 获取支付信息
     */
    public function getPayConfig(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        try {
            $order_sn = $request->get('order_sn');

            $order = FleaOrder::query()->where('order_sn', $order_sn)->firstOrFail();

            if ($order['state'] != 1 || $order['pay_at']) {
                return $this->error('订单已支付');
            }

            //获取下单用户的openid
            $open_id = User::query()->where('id', $order['user_id'])->value('openid');

            $total_amount = $order['total_amount'] * 100;

            $order = [
                'out_trade_no' => $order['order_sn'], //商户订单号
                'body' => '跳蚤市场商品', //商品描述
                'total_fee' => $total_amount, //订单总金额，单位为分
                'openid' => $open_id, //openid
                'attach' => json_encode(['type' => 'flea']), //额外参数自定义参数
                //'sub_mch_id' => '1602262945' //子商户id
            ];

            $result = app('wechat_pay')->miniapp($order);

        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }

        return $this->success($result, '请求成功');
    }

    /**
     * @param $goods :商品信息
     * @param $num :购买数量
     * 检查商品是否能够购买
     */
    private function checkGoods($goods, $num = 1)
    {
        $msg = '';
        switch ($goods) {
            case !$goods:
                $msg = '商品不存在';
                break;
//                case $goods['goods_verify']:
//                    break;
//                case $goods['goods_status']:
//                    $msg = '商品已下架';
//                    break;
//                case $goods['goods_stock'] < $num:
//                    $msg = '库存不足';
//                    break;
            case $goods['status'] != 1:
                $msg = '商品已下架';
                break;
            case $goods['is_sale'] != 0:
                $msg = '商品暂时无法购买';
                break;
            default:
                $msg = true;
        }
        return $msg;
    }

    //获取我买到的的订单列表
    public function myByOrder(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $where = [];
        $state = $request->get('state');
        if ($state) {
            $where[] = ['state', '=', $state];
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        $data = FleaOrder::query()->with(['goods:id,goods_name,goods_images', 'user:phone'])->select('id', 'user_id', 'goods_id', 'order_sn', 'num', 'amount', 'total_amount', 'deal_type', 'state', 'pay_at')->where('user_id', $user_id)->where($where)->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaOrder::query()->where('user_id', $user_id)->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response, '请求成功');

    }

    //确认收货接口
    public function orderComplete(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $order_id = $request->post('order_id');

        DB::beginTransaction();
        try {
            //查询订单是否是登录用户的订单
            $order = FleaOrder::query()->where('id', $order_id)->firstOrFail();

            if ($order && $order['user_id'] == $user_id && $order['state'] == 2) {

                //必须是登录用户的订单并且订单订单状态为待收货

                //订单状态改为待评价
                FleaOrder::query()->where('id', $order_id)->update(['state' => 3, 'confirm_at' => date('Y-m-d H:i:s')]);
                //卖家ID
                $seller_id = $order->user->id;

                //订单金额存入卖家跳蚤市场钱包
                User::query()->where('id', $seller_id)->increment('flea_money', $order['total_amount']);

                //写入日志
                FleaRecord::query()->create([
                    'user_id' => $seller_id,
                    'money' => $order['total_amount'],
                    'order_sn' => $order['order_sn'],
                    'order_id' => $order['id'],
                    'type' => 1,
                    'msg' => '用户确认收货'
                ]);

                DB::commit();
            } else {
                throw new \Exception('订单异常');
            }
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }
        return $this->success();

    }

    //获取我发布的商品列表
    public function myGoods(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        $select = ['id', 'user_id', 'goods_name', 'goods_content', 'goods_images', 'goods_price', 'created_at', 'is_sale'];

        $data = FleaGoodsModel::query()->select($select)->where('is_sale', '<>', 5)->where('user_id', $user_id)->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaGoodsModel::query()->where('is_sale', '<>', 5)->where('user_id', $user_id)->count();
        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response, '请求成功');

    }

    //获取我卖出的商品列表
    public function mySellOrder(Request $request)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $where = [];
        $state = $request->get('state');
        if ($state) {
            $where[] = ['state', '=', $state];
        }

        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        //查询我发布的所有商品ID
        $goods_ids = FleaGoodsModel::query()->where('user_id', $user_id)->pluck('id');

        $data = FleaOrder::query()->with(['goods:id,goods_name,goods_images', 'byUser:id,phone'])->select('id', 'user_id', 'goods_id', 'num', 'amount', 'total_amount', 'deal_type', 'state', 'pay_at')->whereIn('goods_id', $goods_ids)->where($where)->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaOrder::query()->where($where)->whereIn('goods_id', $goods_ids)->count();

        $response['pages'] = ceil($response['count'] / $limit);

        return $this->success($response, '请求成功');
    }

    /**
     * @param $id
     * @return array
     * 订单详情
     */
    public function show($id)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }
        try {
            $data = FleaOrder::query()->with('user:nickname,phone,avatar')->where('user_id', $user_id)->where('id', $id)->firstOrFail();
            $data->goods;
        }catch (\Exception $exception) {
            return $this->error('订单不存在');
        }

        return $this->success($data);
    }

    public function destroy($id)
    {
        $user_id = $this->user_id;
        if (!$user_id) {
            return $this->error('请先登录');
        }

        $res = FleaOrder::destroy($id);

        return $res ? $this->success([], '删除成功') : $this->error();
    }
}
